Filtering Lists in React JS
Filtering Lists in React JS is the process of displaying only those items from an array that satisfy a specific condition. React developers commonly use JavaScript's filter() method to select the required data and the map() method to display the filtered results as JSX elements.
Filtering is useful for implementing search bars, category filters, product listings, student records, employee directories, dashboards, and task management applications.
Course: JustAcademy React JS Training Course
Course Demo: Register for React JS Course Demo
1. What Is Filtering Lists in React?
Filtering lists means selecting specific elements from an array based on a condition and displaying only the matching elements in the user interface.
For example, suppose an application contains a list of five students. If you want to display only students who have passed an examination, you can use the filter() method to select students whose marks are greater than or equal to the passing marks.
Example of a Student List
const students = [
{ id: 1, name: "Rahul", marks: 85 },
{ id: 2, name: "Priya", marks: 42 },
{ id: 3, name: "Amit", marks: 76 },
{ id: 4, name: "Neha", marks: 35 },
{ id: 5, name: "Sneha", marks: 91 }
];
const passedStudents = students.filter(
student => student.marks >= 40
);
console.log(passedStudents);
Output: Rahul, Priya, Amit, and Sneha are included because their marks are at least 40.
Important Points
- The
filter() method checks every element in an array.
- It returns a new array containing elements that satisfy the condition.
- It does not modify the original array.
- It returns an empty array when no elements satisfy the condition.
- React commonly combines
filter() with map() to display the filtered data.
2. What Is the JavaScript filter() Method?
The filter() method is a built-in JavaScript array method. It executes a callback function for each element and includes an element in the resulting array when the callback returns a truthy value.
Syntax
array.filter((item, index, array) => {
return condition;
});
Parameters
| Parameter |
Description |
item |
The current element being checked. |
index |
The position of the current element in the array. |
array |
The original array on which the method is called. |
condition |
The expression that determines whether an element should be included. |
The index and array parameters are optional. In most React filtering operations, you only need the current item.
Simple Example
const numbers = [10, 15, 20, 25, 30];
const filteredNumbers = numbers.filter(
number => number > 20
);
console.log(filteredNumbers);
Output:
[25, 30]
3. Difference Between filter() and map()
The filter() and map() methods serve different purposes when working with React lists.
| Feature |
filter() |
map() |
| Purpose |
Selects elements that match a condition. |
Transforms each element into a new value or JSX element. |
| Output |
A new array containing matching elements. |
A new array containing transformed elements. |
| Condition required |
Usually uses a condition to decide inclusion. |
Does not require a filtering condition. |
| Common React use |
Selecting products by category or name. |
Rendering products as JSX components. |
Example Using Both Methods
const products = [
{ id: 1, name: "Laptop", price: 50000 },
{ id: 2, name: "Mouse", price: 800 },
{ id: 3, name: "Keyboard", price: 1500 },
{ id: 4, name: "Monitor", price: 12000 }
];
const affordableProducts = products.filter(
product => product.price < 5000
);
const productList = affordableProducts.map(
product => product.name
);
console.log(productList);
Output:
["Mouse", "Keyboard"]
Here, filter() selects products priced below ₹5,000, while map() extracts their names.
4. Rendering a Filtered List in React
In React, the filtered array can be generated first and then rendered using JSX. Every rendered list item should have a stable, unique key so React can identify it correctly when the list changes.
Example: Display Active Users
import React from "react";
const users = [
{ id: 1, name: "Rahul", active: true },
{ id: 2, name: "Priya", active: false },
{ id: 3, name: "Amit", active: true },
{ id: 4, name: "Neha", active: false }
];
function UserList() {
const activeUsers = users.filter(
user => user.active
);
return (
<div>
<h2>Active Users</h2>
<ul>
{activeUsers.map(user => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
</div>
);
}
export default UserList;
Explanation
- The
users array contains user objects.
- The
filter() method selects users whose active property is true.
- The
map() method converts each selected user into an element.
- The
key={user.id} attribute gives each list item a stable identity.
- React displays only the active users.
5. Filtering Lists Using Search Input
Search functionality allows users to find specific records by entering a name, title, product, or keyword. In React, the search input is commonly controlled using the useState() Hook.
Example: Search Products by Name
import { useState } from "react";
const products = [
{ id: 1, name: "Laptop", category: "Electronics" },
{ id: 2, name: "Mobile Phone", category: "Electronics" },
{ id: 3, name: "Office Chair", category: "Furniture" },
{ id: 4, name: "Desk", category: "Furniture" }
];
function ProductSearch() {
const [searchTerm, setSearchTerm] = useState("");
const filteredProducts = products.filter(product =>
product.name
.toLowerCase()
.includes(searchTerm.trim().toLowerCase())
);
return (
<div>
<h2>Search Products</h2>
<input
type="text"
placeholder="Search by product name"
value={searchTerm}
onChange={event => setSearchTerm(event.target.value)}
/>
<ul>
{filteredProducts.length > 0 ? (
filteredProducts.map(product => (
<li key={product.id}>
{product.name} - {product.category}
</li>
))
) : (
<li>No products found.</li>
)}
</ul>
</div>
);
}
export default ProductSearch;
How It Works
useState("") stores the current search text.
onChange updates the search text whenever the user types.
trim() removes leading and trailing whitespace.
toLowerCase() makes the search case-insensitive.
includes() checks whether a product name contains the search term.
- The filtered products are displayed automatically after React re-renders the component.
Example: Searching for phone displays “Mobile Phone”. Searching for desk displays “Desk”. If there are no matching products, the application displays “No products found.”
6. Filtering Lists by Category
Category filtering is useful when users need to display items belonging to a particular group, such as electronics, clothing, furniture, courses, or services.
Example: Product Category Filter
import { useState } from "react";
const products = [
{ id: 1, name: "Laptop", category: "Electronics" },
{ id: 2, name: "Headphones", category: "Electronics" },
{ id: 3, name: "Chair", category: "Furniture" },
{ id: 4, name: "Table", category: "Furniture" }
];
function CategoryFilter() {
const [category, setCategory] = useState("All");
const filteredProducts = products.filter(product =>
category === "All" || product.category === category
);
return (
<div>
<h2>Product Categories</h2>
<select
value={category}
onChange={event => setCategory(event.target.value)}
>
<option value="All">All Categories</option>
<option value="Electronics">Electronics</option>
<option value="Furniture">Furniture</option>
</select>
<ul>
{filteredProducts.map(product => (
<li key={product.id}>
{product.name} - {product.category}
</li>
))}
</ul>
</div>
);
}
export default CategoryFilter;
Explanation
The selected category is stored in state. When the user selects a category, the state updates and React displays the matching products. The condition category === "All" || product.category === category allows all products to appear when “All Categories” is selected.
7. Combining Search and Category Filtering
Real-world applications often need multiple filters simultaneously. For example, an online store may let users search by product name and select a category. You can combine these conditions in a single filter() callback.
const filteredProducts = products.filter(product => {
const matchesSearch = product.name
.toLowerCase()
.includes(searchTerm.trim().toLowerCase());
const matchesCategory =
category === "All" || product.category === category;
return matchesSearch && matchesCategory;
});
Explanation:
matchesSearch checks whether the product name matches the search term.
matchesCategory checks whether the selected category matches the product category.
- The
&& operator means both conditions must be true for the product to appear.
- When the category is “All”, the category condition allows every category through, while the search condition still applies.
AND vs. OR Conditions
| Operator |
Meaning |
Example |
&& |
Both conditions must be true. |
Product matches the search and selected category. |
|| |
At least one condition must be true. |
Category is “All” or matches the product category. |
! |
Reverses a Boolean condition. |
!product.outOfStock selects products not marked out of stock. |
8. Filtering Lists by Numeric Values
You can filter arrays using numeric conditions, including price, age, marks, quantity, rating, or salary.
Example: Filter Products by Price
const products = [
{ id: 1, name: "Laptop", price: 55000 },
{ id: 2, name: "Mouse", price: 700 },
{ id: 3, name: "Keyboard", price: 1800 },
{ id: 4, name: "Monitor", price: 14000 }
];
const budgetProducts = products.filter(
product => product.price <= 2000
);
console.log(budgetProducts);
Output: Mouse and Keyboard.
Other Numeric Conditions
// Students who scored 75 or more
const highScorers = students.filter(
student => student.marks >= 75
);
// Employees with a salary above 30000
const highSalaryEmployees = employees.filter(
employee => employee.salary > 30000
);
// Products with a rating of at least 4
const highlyRatedProducts = products.filter(
product => product.rating >= 4
);
9. Filtering Lists Using Boolean Properties
Boolean filtering is useful when an object contains properties such as isActive, isAvailable, isCompleted, or isPublished.
const tasks = [
{ id: 1, title: "Learn React", completed: true },
{ id: 2, title: "Practice JSX", completed: false },
{ id: 3, title: "Build a Project", completed: true }
];
const completedTasks = tasks.filter(
task => task.completed
);
const pendingTasks = tasks.filter(
task => !task.completed
);
console.log(completedTasks);
console.log(pendingTasks);
The first filter selects completed tasks, while the second selects tasks whose completed value is false.
10. Filtering Lists with Multiple Conditions
Multiple conditions allow you to narrow down a list based on several requirements at once.
Example: Filter Employees
const employees = [
{ id: 1, name: "Amit", department: "IT", salary: 45000 },
{ id: 2, name: "Priya", department: "HR", salary: 35000 },
{ id: 3, name: "Rahul", department: "IT", salary: 60000 },
{ id: 4, name: "Neha", department: "IT", salary: 30000 }
];
const filteredEmployees = employees.filter(employee =>
employee.department === "IT" &&
employee.salary >= 40000
);
console.log(filteredEmployees);
Result: Amit and Rahul are selected because they belong to the IT department and earn at least 40,000.
Using OR Conditions
const selectedEmployees = employees.filter(employee =>
employee.department === "HR" ||
employee.salary >= 60000
);
This condition selects employees who work in HR or have a salary of at least 60,000.
11. Filtering Lists with Case-Insensitive Search
Users may type a search term in uppercase, lowercase, or mixed case. Converting both the stored text and search term to lowercase helps make the search case-insensitive.
const names = ["Rahul Sharma", "Priya Patel", "Amit Kumar"];
const searchTerm = "RAHUL";
const results = names.filter(name =>
name.toLowerCase().includes(searchTerm.toLowerCase())
);
console.log(results);
Output:
["Rahul Sharma"]
For object arrays, apply the same approach to a string property such as product.name or user.email. For more advanced searches, consider trimming whitespace and handling missing or non-string values safely.
12. Filtering Lists in React Using useState()
The useState() Hook allows React components to store values that change over time. A filtering interface can use state to keep track of the selected filter and update the displayed list when the selection changes.
Example: Filter Students by Passing Status
import { useState } from "react";
const students = [
{ id: 1, name: "Amit", marks: 80 },
{ id: 2, name: "Priya", marks: 35 },
{ id: 3, name: "Rahul", marks: 65 },
{ id: 4, name: "Neha", marks: 28 }
];
function StudentFilter() {
const [status, setStatus] = useState("All");
const filteredStudents = students.filter(student => {
if (status === "Passed") return student.marks >= 40;
if (status === "Failed") return student.marks < 40;
return true;
});
return (
<div>
<h2>Student Results</h2>
<select
value={status}
onChange={event => setStatus(event.target.value)}
>
<option value="All">All Students</option>
<option value="Passed">Passed</option>
<option value="Failed">Failed</option>
</select>
<ul>
{filteredStudents.map(student => (
<li key={student.id}>
{student.name}: {student.marks}
</li>
))}
</ul>
</div>
);
}
export default StudentFilter;
Important: The filtered list is derived from the original data and the current state. You generally do not need a separate state variable for the filtered array when it can be calculated directly during rendering.
13. Filtering Data Received from an API
React applications often receive lists from APIs. After fetching data, you can filter the stored array according to a search term or selected category.
Example: Fetch and Search Users
import { useEffect, useState } from "react";
function UserDirectory() {
const [users, setUsers] = useState([]);
const [searchTerm, setSearchTerm] = useState("");
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
async function fetchUsers() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users",
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error("Unable to fetch users.");
}
const data = await response.json();
setUsers(data);
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message || "Something went wrong.");
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
fetchUsers();
return () => controller.abort();
}, []);
const filteredUsers = users.filter(user =>
user.name.toLowerCase().includes(
searchTerm.trim().toLowerCase()
)
);
if (loading) return <p>Loading users...</p>;
if (error) return <p>Error: {error}</p>;
return (
<div>
<h2>User Directory</h2>
<input
type="text"
placeholder="Search users"
value={searchTerm}
onChange={event => setSearchTerm(event.target.value)}
/>
{filteredUsers.length === 0 ? (
<p>No matching users found.</p>
) : (
<ul>
{filteredUsers.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
)}
</div>
);
}
export default UserDirectory;
Explanation
useEffect() fetches user data when the component mounts.
useState() stores the users, search text, loading status, and error message.
filter() searches the loaded users by name.
map() renders the filtered users.
- The loading and error states provide feedback while data is being retrieved.
AbortController helps cancel the request when the component is removed.
14. Removing Items from a List Using filter()
The filter() method can also remove items from a displayed list. In React, update state with the new array instead of modifying the existing state array directly.
Example: Delete a Task
import { useState } from "react";
function TaskList() {
const [tasks, setTasks] = useState([
{ id: 1, title: "Learn React" },
{ id: 2, title: "Practice JavaScript" },
{ id: 3, title: "Build a project" }
]);
function deleteTask(id) {
setTasks(currentTasks =>
currentTasks.filter(task => task.id !== id)
);
}
return (
<ul>
{tasks.map(task => (
<li key={task.id}>
{task.title}
{" "}
<button onClick={() => deleteTask(task.id)}>
Delete
</button>
</li>
))}
</ul>
);
}
export default TaskList;
How it works: When the Delete button is clicked, filter() creates a new array containing every task except the task with the selected ID. Calling setTasks() updates the state and React renders the updated list.
15. Filtering Lists and Handling Empty Results
A filtering interface should handle cases where no items match the selected condition. Otherwise, users may see a blank area without understanding what happened.
Example
const filteredProducts = products.filter(product =>
product.category === selectedCategory
);
return (
<div>
{filteredProducts.length > 0 ? (
filteredProducts.map(product => (
<div key={product.id}>
{product.name}
</div>
))
) : (
<p>No products match your filter.</p>
)}
</div>
);
For better usability, you can also provide a Reset Filters button, display the number of matching items, or suggest changing the search term.
16. Filtering Lists with a Reset Button
A reset option allows users to return to the complete list after applying a search or category filter.
const [searchTerm, setSearchTerm] = useState("");
const filteredProducts = products.filter(product =>
product.name.toLowerCase().includes(
searchTerm.trim().toLowerCase()
)
);
return (
<div>
<input
value={searchTerm}
onChange={event => setSearchTerm(event.target.value)}
placeholder="Search products"
/>
<button onClick={() => setSearchTerm("")}>
Reset
</button>
{filteredProducts.map(product => (
<p key={product.id}>{product.name}</p>
))}
</div>
);
Clicking Reset sets the search term to an empty string, allowing all products to match the search condition.
17. Filtering and Sorting Lists
Filtering and sorting can be combined to show only matching items in a particular order. The following example filters products first and then sorts the filtered array by name.
const filteredAndSortedProducts = products
.filter(product =>
product.name.toLowerCase().includes(
searchTerm.trim().toLowerCase()
)
)
.sort((a, b) => a.name.localeCompare(b.name));
Because filter() creates a new array, sorting the filtered result does not mutate the original products array. Avoid calling sort() directly on an array stored in React state or received through props.
18. Common Mistakes While Filtering Lists
| Mistake |
Why It Is a Problem |
Correct Approach |
Using map() when selection is required |
map() transforms each item rather than excluding non-matching items. |
Use filter() to select matching items. |
Forgetting to render with map() |
The filtered data may not be converted into the intended JSX elements. |
Use map() to render the filtered array. |
| Missing keys |
React may show a warning and struggle to track list items properly. |
Use a stable ID such as key={item.id}. |
| Incorrect comparison |
A wrong condition may include or exclude unexpected items. |
Check equality, comparison operators, and data types. |
| Case-sensitive search |
Searches may fail when capitalization differs. |
Normalize text with toLowerCase(). |
| Not handling empty results |
The user may see a blank list. |
Display a suitable empty-state message. |
| Mutating state directly |
Direct mutation can prevent reliable React updates. |
Create a new array and update state using its setter. |
| Using array indexes as keys unnecessarily |
Keys can become unreliable when items are removed or reordered. |
Prefer stable, unique identifiers. |
| Filtering data before it has loaded |
Unexpected values may cause runtime errors. |
Initialize state appropriately and handle loading and error states. |
19. Best Practices for Filtering Lists in React
- Use
filter() to select matching elements and map() to render them.
- Write clear, readable filtering conditions.
- Use stable IDs as keys for rendered list items.
- Keep the original data unchanged when filtering or sorting.
- Use controlled inputs for search boxes and selection controls.
- Normalize text when case-insensitive searches are required.
- Handle empty arrays and no-match results gracefully.
- Keep loading and error states separate when working with API data.
- Calculate filtered results from the source data and current filter values instead of duplicating derived state unnecessarily.
- For large datasets, consider debouncing search input, pagination, virtualization, or server-side filtering when appropriate.
- Use descriptive variable names such as
filteredProducts, activeUsers, and completedTasks.
20. Performance Considerations
For small and medium-sized lists, calling filter() during rendering is usually straightforward and sufficient. For very large arrays or expensive filtering operations, repeated calculations may affect performance.
Using useMemo() for Expensive Filtering
import { useMemo, useState } from "react";
function ProductList({ products }) {
const [searchTerm, setSearchTerm] = useState("");
const filteredProducts = useMemo(() => {
const query = searchTerm.trim().toLowerCase();
return products.filter(product =>
product.name.toLowerCase().includes(query)
);
}, [products, searchTerm]);
return (
<div>
<input
value={searchTerm}
onChange={event => setSearchTerm(event.target.value)}
placeholder="Search products"
/>
<ul>
{filteredProducts.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
}
useMemo() caches a calculated value and recalculates it when its dependencies change. It is an optimization, not a requirement for every filtering operation. The component assumes each product has a string name and a stable id.
21. Real-World Applications of List Filtering
- E-commerce: Filter products by price, category, brand, rating, or availability.
- Student Management: Display students by marks, grade, course, or attendance.
- Employee Management: Filter employees by department, role, salary, or status.
- Task Management: Display completed, pending, or overdue tasks.
- Job Portals: Filter jobs by location, experience, skills, and employment type.
- Blog Websites: Search articles by title, author, category, or tag.
- Admin Dashboards: Filter records by date, status, or assigned user.
- Booking Applications: Display available hotels, appointments, or services according to selected conditions.
22. Mini Project: Product Search and Category Filter
Project Objective: Build a small React component that displays products and allows users to search by name and filter by category.
Requirements
- Create an array of product objects with
id, name, category, and price properties.
- Add a search input for product names.
- Add a category dropdown with an “All Categories” option.
- Combine the search and category conditions using
filter().
- Render matching products using
map().
- Use a stable key for each product.
- Display a message when no products match.
- Add a Reset button to clear the filters.
Sample Data
const products = [
{ id: 1, name: "Laptop", category: "Electronics", price: 55000 },
{ id: 2, name: "Headphones", category: "Electronics", price: 2500 },
{ id: 3, name: "Office Chair", category: "Furniture", price: 7000 },
{ id: 4, name: "Study Table", category: "Furniture", price: 5000 },
{ id: 5, name: "Smartphone", category: "Electronics", price: 20000 }
];
Expected Result
When the user enters “phone” and selects “Electronics”, only matching electronic products containing “phone” in their names should appear. When the search term is cleared and “All Categories” is selected, every product should appear.
Skills Practiced
- JavaScript array methods
- React state management using
useState()
- Controlled input elements
- Conditional rendering
- Rendering arrays with
map()
- Combining multiple filtering conditions
- Empty-state handling and user interaction
23. Interview Questions and Answers
Q1. What is list filtering in React?
Answer: List filtering is the process of selecting elements from an array based on a condition and displaying only the matching elements in a React component.
Q2. Which JavaScript method is used to filter arrays?
Answer: The filter() method selects elements whose callback function returns a truthy value.
Q3. Does filter() modify the original array?
Answer: No. The filter() method returns a new array and does not modify the original array.
Q4. What is the difference between filter() and map()?
Answer: filter() selects elements that match a condition, whereas map() transforms each element into a new value or JSX element.
Q5. How can you implement search functionality in React?
Answer: Store the search term using useState(), update it with an input's onChange handler, filter the source array, and render the matching elements using map().
Q6. Why are keys important when rendering filtered lists?
Answer: Keys help React identify list items between renders, including when elements are inserted, removed, or reordered.
Q7. How do you display a message when no results are found?
Answer: Check whether the filtered array's length is zero and conditionally render an empty-state message.
Q8. Can filter() be used to delete an item from a React state array?
Answer: Yes. Create a new array excluding the selected item's ID, then pass that array to the state setter.
Q9. How do you combine search and category filtering?
Answer: Use one filter() callback that checks both the search condition and the category condition, combining them with the logical AND operator when both must match.
Q10. When should useMemo() be used for filtering?
Answer: Use useMemo() when filtering is expensive and recalculating it on every render could affect performance. It is not necessary for every list.
Q11. How can you make a text search case-insensitive?
Answer: Convert both the searchable text and the search term to lowercase before using a method such as includes().
Q12. Can filter() be used with API data?
Answer: Yes. After the API data is loaded into state, use filter() to select matching records and map() to render them.
24. Practice Exercises
- Create a list of numbers and display only the even numbers.
- Create a list of students and display students who scored at least 60 marks.
- Create a product list and filter products priced below ₹5,000.
- Build a search input that filters employee names.
- Build a dropdown that filters products by category.
- Combine a search box with a category dropdown.
- Create a task list with buttons to display completed and pending tasks.
- Add a Delete button that removes an item using
filter() and React state.
- Fetch users from an API and add search functionality.
- Build a product filtering interface with search, category, price, empty-state handling, and a reset button.
25. Quick Revision Checklist
- Understand the purpose of the JavaScript
filter() method.
- Know how callback conditions determine which elements are included.
- Understand the difference between
filter() and map().
- Know how to render filtered arrays in JSX.
- Use stable keys when rendering list elements.
- Implement search functionality with
useState().
- Filter lists by category, price, status, or multiple conditions.
- Handle empty results, loading states, and errors.
- Update React state immutably when deleting list items.
- Know when memoization or server-side filtering may be useful.
26. Conclusion
Filtering Lists is an important React JS concept that helps developers display relevant information from arrays of data. By combining JavaScript's filter() method with React's map(), state management, controlled inputs, and conditional rendering, you can create search boxes, category filters, dashboards, product catalogs, and interactive data-driven applications.
Practice filtering arrays with different conditions and build small projects to understand how filtered results update when users interact with your application.
Learn More: JustAcademy React JS Training Course
Book a Demo: Register for React JS Course Demo